﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WMS.HelperClasses;
using WHMS.EntityClasses;
using WHMS.HelperClasses;
using SD.LLBLGen.Pro.ORMSupportClasses;

namespace WMS
{
	public partial class ProjectsForm : Form
	{
		int _currentId;

		public ProjectsForm()
		{
			InitializeComponent();

            // these statements are work around as LLBL has a deprecated binding for EntityFactory in design time
            this._projects.EntityFactoryToUse = new WHMS.FactoryClasses.ProjectEntityFactory();
            this._projectPlannedItems.EntityFactoryToUse = new WHMS.FactoryClasses.ProjectItemPlanEntityFactory();
            // End work around //

			var dataForm = new DataMngrFormBase<ProjectEntity>(_projects, dataGridView1, bindingSource1, SaveBtn, SaveResult, DeleteResult);
			dataForm.SetMNInfo(typeof(ProjectContractorEntity), AllList, AssignedList, ContractorFields.Id, ContractorFields.Name, ProjectContractorFields.ContractorId, ProjectContractorFields.ProjectId);
			dataForm.SetMNAssociationButtons(AssignSelectedBtn, AssignAllBtn, UnAssignSelectedBtn, UnAssignAllBtn, SaveDetailsBtn);			
			dataForm.MNSaved += new DataMngrFormBase<ProjectEntity>.RaiseMNSaved(dataForm_MNSaved);
			dataForm.SelectionChanged += new DataMngrFormBase<ProjectEntity>.RaiseSelectionChanged(dataForm_SelectionChanged);
			dataForm.SetMandatoryFields(new List<int>() { 0, 1 });

			var uniqueFields = new Dictionary<int, EntityField2>();
			uniqueFields.Add(0, ProjectFields.Code);
			uniqueFields.Add(1, ProjectFields.Name);
			dataForm.SetUniqueFields(uniqueFields, ProjectFields.Id);

			//Business.GetItemview(_items);
			//DALHelper.GetTypedView(_items, null, new SortExpression(ItemViewFields.NameCodeUnit | SortOperator.Ascending));
		}

		void dataForm_MNSaved(int selectedId)
		{
			MessageBox.Show("تم الحفظ بنجاح.");
		}

		void dataForm_SelectionChanged(int selectedRowIndex)
		{
			var selectedValue = dataGridView1.Rows[selectedRowIndex].Cells[dataGridView1.ColumnCount - 1].Value;
			_currentId = (selectedValue == null)?0:int.Parse(selectedValue.ToString());
			LoadProjectItems();
		    LoadStoreItems();
		}

		DataMngrFormBase<ProjectItemPlanEntity> _projectItemsForm;
       
		private void LoadProjectItems()
		{
			if (_projectItemsForm != null)
			{ 
				_projectItemsForm.Dispose();
				_projectItemsForm = null;
			}
			_projectItemsForm = new DataMngrFormBase<ProjectItemPlanEntity>(_projectPlannedItems, dataGridView3, bindingSource2, SaveItemsBtn, _savedItemsCountLbl, _deletedItemsCountLbl, new RelationPredicateBucket(ProjectItemPlanFields.ProjectId == _currentId));
			_projectItemsForm.SetNumericFields(new List<int> { 1 });
			_projectItemsForm.SetMandatoryFields(new List<int>() { 0});
			_projectItemsForm.BeforeSave += new DataMngrFormBase<ProjectItemPlanEntity>.RaiseBeforeSave(dataForm_BeforeSave);

			if (_currentId == 0)
			{
				dataGridView3.Enabled = false;
				SaveItemsBtn.Enabled = false;
			}
			else
			{
				dataGridView3.Enabled = true;
				SaveItemsBtn.Enabled = true;
			}
		}

        private void LoadStoreItems()
        {
            //bindingSource3.DataSource=

            if (_currentId == 0)
            {
                gridStore.Enabled = false;
                SaveItemsBtn.Enabled = false;
            }
            else
            {
                gridStore.Enabled = true;
                SaveItemsBtn.Enabled = true;
            }
        }
		void dataForm_BeforeSave(IEntityCollection2 collectionToBeSaved)
		{
			var uniqueCollection = new EntityCollection<ProjectItemPlanEntity>();
			var toBeDeletedCollection = new EntityCollection<ProjectItemPlanEntity>();

			foreach (ProjectItemPlanEntity projectItem in collectionToBeSaved)
			{
				if (projectItem.IsDirty  && projectItem.ItemId > 0)
				{
					projectItem.ProjectId = _currentId;
				}

				var matchingitem = (from t in uniqueCollection
									where t.ItemId == projectItem.ItemId
									select t).FirstOrDefault();

				if (matchingitem == null)
				{
					uniqueCollection.Add(projectItem);
					continue;
				}

				matchingitem.Quantity += projectItem.Quantity;
				toBeDeletedCollection.Add(projectItem);
			}

			foreach (var entity in toBeDeletedCollection)
			{
			    collectionToBeSaved.Remove(entity);
			}						
		}

		private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex == ItemCode.Index)
			{
				var dt = Business.GetItemDetails(dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
				if (dt.Rows.Count <= 0)
					return;

                for (int i = 0; i < dataGridView3.Rows.Count; i++)
                {
                    if (dataGridView3.Rows[i].Cells[ItemId.Index].Value != null &&
                        (int)dataGridView3.Rows[i].Cells[ItemId.Index].Value == (int)dt.Rows[0][0])
                    {
                        MessageBox.Show("تم اضافة هذا الصنف من قبل", "خطأ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dataGridView3.Rows.RemoveAt(e.RowIndex);
                        return;
                    }
                }

				dataGridView3.Rows[e.RowIndex].Cells[ItemId.Index].Value = (int)dt.Rows[0][0];
				dataGridView3.Rows[e.RowIndex].Cells[ItemName.Index].Value = (string)dt.Rows[0][1];
				dataGridView3.Rows[e.RowIndex].Cells[ItemUnit.Index].Value = (string)dt.Rows[0][2];				
			}
		}

		private void dataGridView3_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
		{
			foreach (DataGridViewRow row in dataGridView3.Rows)
			{
				var item = (ProjectItemPlanEntity)row.DataBoundItem;
				if (item == null)
					continue;

				var dt = Business.GetItemDetails(item.ItemId);
				if (dt.Rows.Count <= 0)
					continue;

				row.Cells[ItemCode.Index].Value = (string)dt.Rows[0][0];
				row.Cells[ItemName.Index].Value = (string)dt.Rows[0][1];
				row.Cells[ItemUnit.Index].Value = (string)dt.Rows[0][2];				
			}
		}

        private void gridStore_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                var dt = Business.GetStoreDetails(gridStore.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
                if (dt.Rows.Count <= 0)
                    return;

                for (int i = 0; i < gridStore.Rows.Count; i++)
                {
                    if (gridStore.Rows[i].Cells[3].Value != null &&
                        (int) gridStore.Rows[i].Cells[3].Value == (int) dt.Rows[0][0])
                    {
                        MessageBox.Show("تم اضافة هذا المخزن من قبل", "خطأ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        gridStore.Rows.RemoveAt(e.RowIndex);
                        return;
                    }
                }

                gridStore.Rows[e.RowIndex].Cells[0].Value = dt.Rows[0][1];
                gridStore.Rows[e.RowIndex].Cells[1].Value = (string) dt.Rows[0][2];
                gridStore.Rows[e.RowIndex].Cells[2].Value = (string) dt.Rows[0][3];
                gridStore.Rows[e.RowIndex].Cells[3].Value = (int)dt.Rows[0][0];

            }
        }

        private void saveStoresBtn_Click(object sender, EventArgs e)
        {
            var uniqueCollection = new EntityCollection<ProjectItemPlanEntity>();
            var toBeDeletedCollection = new EntityCollection<ProjectItemPlanEntity>();

            //foreach (ProjectItemPlanEntity projectItem in )
            //{
            //    if (projectItem.IsDirty && projectItem.ItemId > 0)
            //    {
            //        projectItem.ProjectId = _currentId;
            //    }

            //    var matchingitem = (from t in uniqueCollection
            //                        where t.ItemId == projectItem.ItemId
            //                        select t).FirstOrDefault();

            //    if (matchingitem == null)
            //    {
            //        uniqueCollection.Add(projectItem);
            //        continue;
            //    }

            //    matchingitem.Quantity += projectItem.Quantity;
            //    toBeDeletedCollection.Add(projectItem);
            //}

            //foreach (var entity in toBeDeletedCollection)
            //{
            //    collectionToBeSaved.Remove(entity);
            //}						
        }

        private void btnSearchProject_Click(object sender, EventArgs e)
        {
            string name;
            var filter = new RelationPredicateBucket();
            var searchForm = new SearchForm(ProjectFields.Code, ProjectFields.Name, ProjectFields.ActualStartDate, filter,
                                            () => Business.GetRunningAndGeneralProjects());
            
            if (searchForm.ShowDialog() == DialogResult.OK)
                  name = searchForm.Name;
        }

	}
}
